package at.fhooe.mcm.lri.mdmpoc.warehouse.dao.jdo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import at.fhooe.mcm.lri.mdmpoc.warehouse.dao.PMF;
import at.fhooe.mcm.lri.mdmpoc.warehouse.dao.TimingResultDao;
import at.fhooe.mcm.lri.mdmpoc.warehouse.datamodel.TimingResult;


@SuppressWarnings("unchecked")
public class TimingResultJdoDao implements TimingResultDao {
	private static final PersistenceManagerFactory pmf = PMF.getFactory();

	private synchronized void getResults(Collection<TimingResult> timings, Object queryResult) {
		for (TimingResult tr : (Collection<TimingResult>) queryResult) {
			timings.add(tr);
		}
	}
	@Override
	public  synchronized Collection<TimingResult> findAll() {
		List<TimingResult> timings = new ArrayList<TimingResult>();
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			Query query = pm.newQuery(TimingResult.class);
			getResults(timings, query.execute());
		} finally {
			pm.close();
		}
		return timings;
	}

	@Override
	public  synchronized TimingResult findById(Long key) {
		TimingResult tr = null;

		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			tr = pm.getObjectById(TimingResult.class, key);
		} finally {
			pm.close();
		}
		return tr;
	}

	@Override
	public synchronized void insertTimingResult(TimingResult tr) {
		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.makePersistent(tr);
		} finally {
			pm.close();
		}
	}
	@Override
	public  synchronized TimingResult updateTimingResult(TimingResult timingResult) {
		TimingResult tr = null;

		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.currentTransaction().begin();

			tr = pm.getObjectById(TimingResult.class, timingResult.getKey());
			tr.setAction(timingResult.getAction());
			tr.setDuration(timingResult.getDuration());
			tr.setItems(timingResult.getItems());
			tr.setUsername(timingResult.getUsername());
			tr.setCpuMegaCycles(timingResult.getCpuMegaCycles());
			tr.setCpuSeconds(timingResult.getCpuSeconds());
			tr.setDate(timingResult.getDate());
			pm.makePersistent(tr);

			pm.currentTransaction().commit();
		} catch (RuntimeException ex) {
			pm.currentTransaction().rollback();
			throw ex;
		} finally {
			pm.close();
		}
		return tr;
	}
	@Override
	public synchronized void deleteTimingResult(TimingResult timingResult) {
		TimingResult tr = null;

		PersistenceManager pm = pmf.getPersistenceManager();
		try {
			pm.currentTransaction().begin();
			tr = pm.getObjectById(TimingResult.class, timingResult.getKey());
			if (tr != null)
				pm.deletePersistent(tr);
			pm.currentTransaction().commit();
		} catch (RuntimeException ex) {
			pm.currentTransaction().rollback();
			throw ex;
		} finally {
			pm.close();
		}
	}
	@Override
	public synchronized int getNextFreeId() {
		return this.findAll().size()+1;
	}
}
